package com.nuanshui.heatedloan.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.nuanshui.heatedloan.entity.cms.security.Module;
import com.nuanshui.heatedloan.entity.cms.security.Role;
import com.nuanshui.heatedloan.service.cms.security.ModuleService;
import com.nuanshui.heatedloan.service.cms.security.RoleService;
import com.nuanshui.heatedloan.util.dwz.DwzPage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
/**
 * 角色的控制器
 */
@Controller
@RequestMapping("/cms/manage/role")
public class ApiRoleController extends ApiController {

	@Autowired
	private RoleService roleService;

	@Autowired
	private ModuleService moduleService;

	/**
	 * 打开创建角色的界面
	 */
	//@RequiresPermissions("Role:save")
	@RequestMapping(value = "/preCreate", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String preCreate() {
		Map<String, Object> map = new  HashMap<String, Object>();
		map.put("list", moduleService.getApiTree().get(0));
		return success(  map  );
	}

	/**
	 * 创建角色
	 */
//	@RequiresPermissions("Role:save")
	@RequestMapping(value = "/create", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String create(String body) {
		Role role =  refactor(body);
		roleService.save(role);
		return success();
	}

	/**
	 * 重新组装PermissionList（将test:save,test:edit的形式切分成List）
	 */
	private Role refactor(final String body) {
		JSONObject jsonObject =  JSON.parseObject(body);
		Role role = new Role();
		role.setId(jsonObject.getLong("id"));
		role.setName(jsonObject.getString("name"));
		jsonObject =  jsonObject.getJSONObject("permissionMap");
		Set<String> keys = jsonObject.keySet();
		List<String> allList = Lists.newArrayList();
		for(String key :keys){	
			JSONArray jsonArray =  jsonObject.getJSONArray(key);
			int length = jsonArray.size();
			for(int i =0;i<length;i++){
				String value = jsonArray.getString(i);
				allList.add(key+":"+value);
			}		
		}
		role.setPermissionList(allList);
		return role;
	}

	/**
	 * 打开修改角色的界面
	 */
//	@RequiresPermissions("Role:edit")
	@RequestMapping(value = "/get/{id}", produces = "application/json;charset=UTF-8" )
	@ResponseBody
	public String preUpdate(@PathVariable final Long id ) {
		Role role = roleService.get(id);
		if(role == null) role = new Role();
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("module", moduleService.getApiTree().get(0));
		role.setNeedPermission(true);
		Module module = moduleService.getTree();
		Map<String, List<String>> target = new LinkedHashMap<String, List<String>>();
		
		test(module, role.getPermissionMap(), target); //递归 去排序，根据树的节点。
		role.setPermissionMap(target);
		map.put("role", role);
		return success(  map );
	}
	
	
	private void test(Module module, Map<String, List<String>> source, Map<String, List<String>> target){
		List<Module>  childes = module.getChildren();
		
		String sn = module.getSn();
		if(StringUtils.isNotEmpty(sn) && source.get(sn) == null){//表示并没有这个key，那么就创建一个空的
			List<String> list = Lists.newArrayList();
			target.put(sn, list);
		}
		else {
			if(StringUtils.isNotEmpty(sn)){
				List<String> list = source.get(sn);
				target.put(sn, list);
			}
		}
		if(childes.size() > 0){
			for(Module childrenModule : childes){
				test(childrenModule, source, target);
			}
		}
	}

	/**
	 * 修改角色
	 */
//	@RequiresPermissions("Role:edit")
	@RequestMapping(value = "/update", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String update(String body) {	
		
		Role role =  refactor(body);
		roleService.updateRole(role);
		Map<String,Object>  map  = new HashMap<String,Object>();
		map.put("list",role);
		return success( map );
	}


	/**
	 * 删除角色
	 */
//	@RequiresPermissions("Role:delete")
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	public String delete(final Long id) {
		
		Role role = roleService.get(id);
		
		if(role.getDefaultRole()!= null && role.getDefaultRole() == 1){
			return fail("默认角色不允许删除！！！");
		}
		
		roleService.delete(id);
		return success();
	}

	/**
	 * 查看角色列表
	 * 
	 * @return
	 */
	//@RequiresPermissions("Role:view")
	@RequestMapping(value = "/list", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String list(final DwzPage page, String query) {
		List<Role> roles = null;
		if (StringUtils.isEmpty(query) || DEFAULTQUERYSTR.equals(query)) {
			roles = roleService.findAll(page);
		} else {
			Role role = JSON.parseObject(query, Role.class);
			roles = roleService.findAll(page, role);
		}
		final Map<String, Object> map = new HashMap<String,Object>();
		//map.put("page", page);
		map.put("list", roles);
		map.put("total",page.getTotalCount());
		//map.put("keywords", keywords);
		return success(map);
	}

}
